package com.tttshaoqi.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.tttshaoqi.entity.SysUserAuth;
import com.tttshaoqi.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.function.Supplier;

/**
 * @author tttshaoqi
 * &#064;create 2025-07-30-22:04
 */
@Component
public class TokenAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {

        // 获取request
        HttpServletRequest request = object.getRequest();
        // 获取token
        String token = request.getHeader("token");
        // token为空返回 403
        if(StrUtil.isBlank(token)){
            return new AuthorizationDecision(false);
        }
        // 解析token
        Claims claims = JwtUtil.parseJWT("tttshaoqi", token);
        // 解析失败返回 403
        if(claims==null){
            return new AuthorizationDecision(false);
        }
        // 获取用户信息
        String jsonStr = JSONUtils.toJSONString(claims.get("user"));
        SysUserAuth user = JSONObject.parseObject(jsonStr,SysUserAuth.class);
        // 将用户信息填入security 上下文
        UsernamePasswordAuthenticationToken upat = new UsernamePasswordAuthenticationToken(user,user.getPassword(),user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(upat);

        // 获取请求路径
        String uri = request.getRequestURI();
        // 验证权限
        if(user.getRoles().contains("USER")){
            if(uri.equals("/hello/user")){
                return new AuthorizationDecision(true);
            }
        }
        if(user.getRoles().contains("ADMIN")){
            if(uri.equals("/hello/admin")){
                return new AuthorizationDecision(true);
            }
        }

        return new AuthorizationDecision(false);
    }
}
